package com.zyms.controller.baseController;

import com.zyms.def.Constant;
import com.zyms.log.LogFactory;
import com.zyms.module.result.ReturnCode;
import com.zyms.module.user.User;
import com.zyms.myRunTime.MyRunTimeExcption;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Baggio on 2018-1-24.
 */
public abstract class BaseController {
    protected Logger logger = LogFactory.getLogger(getClass());
    @Autowired
    protected  HttpServletRequest request;
    @Autowired
    protected  HttpServletResponse response;
    @Autowired
    protected HttpSession session;
    /**
     * 从request的参数传递提取成Map<String , String>对象
     * 同时会从session中获取userId和userType
     *
     * @return
     */
    protected Map<String, String> showRequestParameters() {

        Enumeration<?> paramNames = request.getParameterNames();
        Map<String, String> map = new HashMap<String, String>();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement().toString();
            String paramValue = request.getParameter(paramName);
            map.put(paramName, paramValue);
            System.out.println(paramName + "[:]" + paramValue);
        }

        try {
            map.put("userId", String.valueOf(getUserIdBySession().getTid()));
        } catch (MyRunTimeExcption e) {
            logger.error(e.getMessage());
        }

        return map;
    }

    /**
     * 从session中获取user，没有则抛错
     * @return
     */
    protected User getUserIdBySession() {
        User user =null;
        try {
            logger.info("getUserIdBySession====>>>"+session.getId());
            user=  (User) session.getAttribute(Constant.SESSION_KEY_USER_LOGIN);
            if(user==null){
                throw new MyRunTimeExcption(ReturnCode.USER_IS_NOT_LOGIN.getCode(),ReturnCode.USER_IS_NOT_LOGIN.getMsg());
            }
            if(user.getTid()==null){
                throw new MyRunTimeExcption(ReturnCode.USER_IS_INEXISTENCE.getCode(),ReturnCode.USER_IS_INEXISTENCE.getMsg());
            }
        } catch (Exception e) {
            logger.info("用户没有登录！");
            throw new MyRunTimeExcption(ReturnCode.USER_IS_NOT_LOGIN.getCode(),ReturnCode.USER_IS_NOT_LOGIN.getMsg());
        }
        if (user   == null || user.getTid()==null || user.getTid()==0) {
            logger.info("你还没有登录！");
            throw new MyRunTimeExcption(ReturnCode.USER_IS_NOT_LOGIN.getCode(),ReturnCode.USER_IS_NOT_LOGIN.getMsg());
        }
        return user;
    }
}
